package kr.couponplay.android.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.SortingType;
import kr.couponplay.android.adapter.DealListAdapter;
import kr.couponplay.android.adapter.AdvertiseAdapter;
import kr.couponplay.android.domain.ButtonView;
import kr.couponplay.android.domain.ButtonView.MenuType;
import kr.couponplay.android.domain.Deal;
import kr.couponplay.android.domain.SortingView;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak") 
public class MainActivity extends BackPressActivity implements OnClickListener, OnItemClickListener {
	private TextView titleTextView;
	private ProgressDialog loadindDialog;
	
	private ListView dealListView;
	private LinearLayout dealListHeaderView;
	private LinearLayout dealListFooterView;
	private TextView moreTextView;
	
	private List<SortingView> sortingViews = new ArrayList<SortingView>();
	private List<ButtonView> buttonViews = new ArrayList<ButtonView>();

	private DealListAdapter dealListAdapter;
	private AdvertiseAdapter advertiseAdapter;

	private String menuType = MenuType.HOME.name();
	private boolean isAddDeal = false;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        dealListAdapter = new DealListAdapter(this, R.layout.deal_list_row, new ArrayList<Deal>());
        
        drawTitleView();
        setMenuType();
        setSortingView();
        
        Button homeButton = (Button)findViewById(R.id.homeButton);
        buttonViews.add(new ButtonView(homeButton, MenuType.HOME));
        homeButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
//        		Toast.makeText(mContext, "홈으로 이동 중", Toast.LENGTH_SHORT).show(); 
       			finish();
       			AppContext.clearSearch();
       			Intent intent = new Intent(mContext, MainActivity.class);
       			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
       			intent.putExtra("menuType", MenuType.HOME.name());
       			startActivity(intent);
        	}
        });
        
        Button recentButton = (Button)findViewById(R.id.recentButton);
        buttonViews.add(new ButtonView(recentButton, MenuType.RECENT));
        recentButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		finish();
        		AppContext.clearSearch();
        		AppContext.searchType = "FREE_DEAL";
        		Intent intent = new Intent(mContext, MainActivity.class);
        		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        		intent.putExtra("title", "최근 본 상품");
        		intent.putExtra("menuType", MenuType.RECENT.name());
        		startActivity(intent);
        	}
        });
        
        Button freeButton = (Button)findViewById(R.id.freeButton);
        buttonViews.add(new ButtonView(freeButton, MenuType.FREE));
        freeButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		finish();
        		AppContext.clearSearch();
        		AppContext.searchType = "FREE_DEAL";
        		Intent intent = new Intent(mContext, MainActivity.class);
        		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        		intent.putExtra("title", "무료 상품");
        		intent.putExtra("menuType", MenuType.FREE.name());
        		startActivity(intent);
        	}
        });
        
        Button categoryButton = (Button)findViewById(R.id.categoryButton);
        buttonViews.add(new ButtonView(categoryButton, MenuType.CATEGORY));
        categoryButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent intent = new Intent(mContext, CategoryActivity.class);
        		startActivity(intent);
        	}
        });
        
        Button searchButton = (Button)findViewById(R.id.searchButton);
        buttonViews.add(new ButtonView(searchButton, MenuType.SEARCH));
        searchButton.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent intent = new Intent(mContext, SearchActivity.class);
        		startActivity(intent);
        	}
        });
        setSelectedButton();
		
        LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
        dealListHeaderView = (LinearLayout)inflater.inflate(R.layout.deal_list_row_header, null);
		dealListFooterView = (LinearLayout)inflater.inflate(R.layout.deal_list_row_footer, null);
		moreTextView = (TextView)dealListFooterView.findViewById(R.id.listMoreViewTV);
    	
    	dealListView = (ListView) findViewById(R.id.deal_list_view);
		drawDealListHeaderView();
		dealListView.addFooterView(dealListFooterView);
		dealListView.setAdapter(dealListAdapter);
		dealListView.setOnItemClickListener(this);
        
       	getDataFromServer();
    }

	private void setMenuType() {
		menuType = getIntent().getStringExtra("menuType");
        if (menuType == null) {
        	menuType = MenuType.HOME.name();
        }
	}

	private void drawTitleView() {
		titleTextView = (TextView)findViewById(R.id.app_title);
        String title = getIntent().getStringExtra("title");
        if (title == null) {
        	title = titleTextView.getText().toString();
        }
        titleTextView.setText(title);
	}

	private void setSortingView() {
		LinearLayout linearLayout = (LinearLayout)findViewById(R.id.sorting_group_layout);

		if (MenuType.RECENT.name().equals(menuType) || MenuType.FREE.name().equals(menuType)) {
			linearLayout.setVisibility(View.INVISIBLE);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 0);
			linearLayout.setLayoutParams(params);
		} else {
			linearLayout.setVisibility(View.VISIBLE);

			TextView orderPopular = (TextView)findViewById(R.id.order_popular);
	        orderPopular.setOnClickListener(this);
	        sortingViews.add(new SortingView(orderPopular, SortingType.HIT));
	        
	        TextView salePopular = (TextView)findViewById(R.id.order_sale);
	        salePopular.setOnClickListener(this);
	        sortingViews.add(new SortingView(salePopular, SortingType.BUY_COUNT));
	        
	        TextView pricePopular = (TextView)findViewById(R.id.order_price);
	        pricePopular.setOnClickListener(this);
	        sortingViews.add(new SortingView(pricePopular, SortingType.PRICE_ROW));
	        
	        TextView discountPopular = (TextView)findViewById(R.id.order_discount);
	        discountPopular.setOnClickListener(this);
	        sortingViews.add(new SortingView(discountPopular, SortingType.RATE));
	        
	        drawSortingView(orderPopular);
		}
	}

    private void setSelectedButton() {
		for (ButtonView buttonView : buttonViews) {
			if (buttonView.getMenuType().name().equals(menuType)) {
				buttonView.getButton().setBackgroundColor(Color.parseColor("#303645"));
				buttonView.getButton().setSelected(true);
			} else {
				buttonView.getButton().setBackgroundColor(Color.parseColor("#4C505B"));
			}
		}
	}
    
	private void drawAdvertiseListView() {
		try {
			Gallery gallery = (Gallery) dealListHeaderView.findViewById(R.id.mainAdver);
        	
        	if (advertiseAdapter == null) {
        		advertiseAdapter = new AdvertiseAdapter(dealListHeaderView.getContext(), R.layout.deal_list_row_header, AppContext.getMainDealList().getDeals());
        	}
        	Random oRandom = new Random();
        	int position = oRandom.nextInt(AppContext.getMainDealList().getDeals().size());
        	gallery.setAdapter(advertiseAdapter);
        	gallery.setSelection(position);
    		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
    			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    				TextView mainDealTitle = (TextView) dealListHeaderView.findViewById(R.id.mainDealTitleTextView);
    				selectDot(position);
    				mainDealTitle.setText(advertiseAdapter.getItem(position).getTitle());
    			}

    			public void onNothingSelected(AdapterView<?> parent) {
    			}
    		});
    		gallery.setOnItemClickListener(new OnItemClickListener() {
    			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(advertiseAdapter.getItem(position).getDetailViewUrl())));
    			}
    		});
    		
        	LinearLayout layout = (LinearLayout)dealListHeaderView.findViewById(R.id.dotPanel);
        	createDotPanel(this, layout, AppContext.getMainDealList().getTotalCount());
		} catch (Exception e) {
			Log.e(AppContext.TAG, e.getMessage(), e);
		}
	}

	private void drawDealListView() {
		if (!isAddDeal) {
			dealListAdapter.clear();
		}
		
		for (Deal each : AppContext.dealList.getDeals()) {
			dealListAdapter.add(each);
		}

		dealListAdapter.notifyDataSetChanged();
		drawDealListFooterView();
	}
	
	private void drawDealListHeaderView() {
		if (MenuType.HOME.name().equals(menuType) && dealListView.getHeaderViewsCount() == 0) {
			drawAdvertiseListView();
			dealListView.addHeaderView(dealListHeaderView);
		}
	}	
	
	private void drawDealListFooterView() {
		int dealCount = dealListView.getCount() - dealListView.getHeaderViewsCount() - dealListView.getFooterViewsCount();
		String text = "더보기";
		if (!canMoreDeal()) {
			text = "끝";
		}
		text = text + " (" + dealCount + "/" + AppContext.dealList.getTotalCount() + ")";
		moreTextView.setText(text);
	}	
	
	private void drawSortingView(View view) {
		for (SortingView sortingView : sortingViews) {
			if (view == sortingView.getTextView()) {
				sortingView.getTextView().setBackgroundColor(Color.parseColor("#303645"));
				sortingView.getTextView().setTextColor(Color.parseColor("#ffffff"));
			} else {
				sortingView.getTextView().setBackgroundColor(Color.parseColor("#4C505B"));
				sortingView.getTextView().setTextColor(Color.parseColor("#ffffff"));
			}
		}		
	}
	
	private boolean canMoreDeal() {
		return (dealListView.getCount() - dealListView.getHeaderViewsCount() - dealListView.getFooterViewsCount()) < AppContext.dealList.getTotalCount();
	}
	
	ImageView [] imageView;
	private void createDotPanel(Context context, LinearLayout layout, int count){
		imageView = new ImageView[count];
		for(int i=0;i<count;i++){
			imageView[i] = new ImageView(context);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, 0);
			params.width = LayoutParams.WRAP_CONTENT;
			params.height = LayoutParams.WRAP_CONTENT;
			params.topMargin = 2;
			params.bottomMargin = 2;
			params.leftMargin= 7;
			params.gravity = Gravity.CENTER;
			imageView[i].setLayoutParams(params);
			imageView[i].setImageResource(R.drawable.circle_off);
			layout.addView(imageView[i]);
		}
	}
	   
	private void selectDot(int position){
		for(int i=0; i<imageView.length; i++) {
			if (i == position) {
				imageView[i].setImageResource(R.drawable.circle_on);
			} else {
				imageView[i].setImageResource(R.drawable.circle_off);
			}
		}
	}
	
	private void getDataFromServer() {
    	loadindDialog = ProgressDialog.show(this, null, "데이터 수신중입니다.", true, false);
    	
        Thread thread = new Thread(new Runnable() {
            public void run() {
            	try {
            		AppContext.dealList = dao.findAll(menuType);
            	} catch (Exception e) {
            		Log.e(AppContext.TAG, e.getMessage(), e);
            	}
        		handler.sendEmptyMessage(0);
            }
        });
        thread.start();
    }
    
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            loadindDialog.dismiss();
            drawDealListView();	
        }
    };
    
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		boolean isMoreEvent = id < 0;
		if (isMoreEvent && canMoreDeal()) {
			AppContext.page++;
			isAddDeal = true;
			getDataFromServer();
		} else if (isMoreEvent) {
			Toast.makeText(mContext, "마지막입니다.", Toast.LENGTH_SHORT).show(); 
		} else {
			Uri uri = Uri.parse(dealListAdapter.getItem(position - dealListView.getHeaderViewsCount()).getDetailViewUrl());
			startActivity(new Intent(Intent.ACTION_VIEW, uri));
		}
	}
	
	@Override
	public void onClick(View view) {
		for (SortingView sortingView : sortingViews) {
			if (view == sortingView.getTextView()) {
				AppContext.sortingType = sortingView.getSortingType();
			}
		}
		dealListView.setSelection(0);
		isAddDeal = false;
		drawSortingView(view);
		getDataFromServer();
	}	
}
